package com.shxc.smarttrade.tigerwit.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.payeasenet.up.lib.utils.NetWork;
import com.payeasenet.up.lib.utils.ViewUtils;
import com.shxc.smarttrade.MyApplication;
import com.shxc.smarttrade.R;
import com.shxc.smarttrade.currency.model.CurrencyModel;
import com.shxc.smarttrade.info.Contents;
import com.shxc.smarttrade.old.activity.RechargeResultActivity;
import com.shxc.smarttrade.old.activity.RechargeWebViewActivity;
import com.shxc.smarttrade.old.utils.Arith;
import com.shxc.smarttrade.old.utils.BaseUtils;
import com.shxc.smarttrade.old.utils.SpUtils;
import com.shxc.smarttrade.utils.analysis.JsonAnalysisModel;
import com.shxc.smarttrade.utils.analysis.JsonAnalysisUtils;
import com.shxc.smarttrade.tigerwit.base.TigerwitBaseActivity;
import com.shxc.smarttrade.tigerwit.model.ComfirmdepositModel;
import com.shxc.smarttrade.tigerwit.model.RateModel;
import com.shxc.smarttrade.utils.Loger;
import com.shxc.smarttrade.utils.MyOkHttpUtils;
import com.shxc.smarttrade.utils.ToastUtils;
import com.unionpay.UPPayAssistEx;

import org.json.JSONException;
import org.json.JSONObject;
import org.xchris.view.annotation.ContentView;
import org.xchris.view.annotation.Event;
import org.xchris.view.annotation.ViewInject;

import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;

/**
 * 老虎 - 充值
 */
@ContentView(R.layout.activity_tigerwit_recharge)
public class TigerWitRechargeActivity extends TigerwitBaseActivity {

    @ViewInject(R.id.title_textview)
    TextView title_textview;
    @ViewInject(R.id.left_imageview)
    ImageView left_imageview;
    @ViewInject(R.id.rmb_textview)
    TextView rmb_textview;//约合人民币
    @ViewInject(R.id.rate_textview)
    TextView rate_textview;//当前汇率
    @ViewInject(R.id.edittext)
    EditText edittext;//输入框

    private double rate = 0.0;
    private double money = 0.0;
    private double rmbAmount = 0.0;
    private String orderNo;
    private String payStatus;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        title_textview.setText("入金");
        left_imageview.setVisibility(View.VISIBLE);
        initListener();
        rate();
    }

    @Event({R.id.left_imageview, R.id.jump_textview})
    private void onClickk(View view) {

        switch (view.getId()) {
            case R.id.left_imageview:
                finish();
                break;
            case R.id.jump_textview:
                //前往充值

                //先请求服务器，获取流水号和计算后的金额
                if (money < 50) {
                    ToastUtils.showToast("请按要求输入金额");

                } else {
                    comfirmdeposit();
                }

                break;
        }
    }


    /**
     * 初始化文本框监听器
     */
    private void initListener() {
        edittext.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String text = edittext.getText().toString();
                if (TextUtils.isEmpty(text)) {
                    money = 0;
                    rmb_textview.setText("约合人民币：¥ 0.00");
                    return;
                }

                try {
                    money = Double.parseDouble(text);
                    if (money < 50) {
                        rmb_textview.setText("约合人民币：¥ " + BaseUtils.getDigitsData(Arith.round4(Arith.mul(money, rate), 2), 2));
                        money = 0;
                    } else {
                        rmb_textview.setText("约合人民币：¥ " + BaseUtils.getDigitsData(Arith.round4(Arith.mul(money, rate), 2), 2));
                    }
                } catch (Exception e) {
                    ToastUtils.showToast("请输入正确金额");
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    //汇率
    private void rate() {
        loadingDialog.show();
        Map<String, Object> map = new HashMap<>();
        map.put("userId", spImp.getUserId());

        MyOkHttpUtils.getServiceDatas(map, Contents.DEPOSIT_TODEPOSIT, new MyOkHttpUtils.ServiceStatus() {
            @Override
            public void success(String response, int d) {
                Loger.e("response", response);
                if (response != null) {
                    JsonAnalysisModel jam = JsonAnalysisUtils.jsonAnalysis(response, RateModel.class);
                    if (jam.isSuccess()) {
                        RateModel model = (RateModel) jam.getData();
                        rate = model.getData().getRate();
                        rate_textview.setText("(当前汇率：1美元≈" + rate + "人民币)");
                    } else {
                        ToastUtils.showToast(jam.getMsg());
                    }
                }
                loadingDialog.dismiss();
            }

            @Override
            public void faild(Call call, Exception e, int id) {
                loadingDialog.dismiss();
            }
        });
    }

    //确认充值
    private void comfirmdeposit() {
        loadingDialog.show();
        Map<String, Object> map = new HashMap<>();
        map.put("userId", spImp.getUserId());
        map.put("amount", money);

        MyOkHttpUtils.getServiceDatas(map, Contents.DEPOSIT_COMFIRMDEPOSIT, new MyOkHttpUtils.ServiceStatus() {
            @Override
            public void success(String response, int d) {
                Loger.e("response", response);
                if (response != null) {
                    JsonAnalysisModel jam = JsonAnalysisUtils.jsonAnalysis(response, ComfirmdepositModel.class);
                    if (jam.isSuccess()) {
                        ComfirmdepositModel model = (ComfirmdepositModel) jam.getData();

                        rmbAmount = model.getData().getInfo().getRmbAmount();
                        orderNo = model.getData().getInfo().getOrderNo();

                        //跳转到确认支付页面

                        String dispachUrl = model.getData().getInfo().getDispatchUrl();
                        if (TextUtils.isEmpty(dispachUrl) || dispachUrl.equals("null")) {
                            startPayMoney();
                        } else {
                            Intent intent = new Intent(TigerWitRechargeActivity.this, RechargeWebViewActivity.class);
                            intent.putExtra("name", "充值");
                            intent.putExtra("url", dispachUrl);
                            startActivity(intent);
                            overridePendingTransition(R.anim.slide_bottom_in, R.anim.slide_bottom_in);
                        }
                    } else {
                        ToastUtils.showToast(jam.getMsg());
                    }
                }
                loadingDialog.dismiss();
            }

            @Override
            public void faild(Call call, Exception e, int id) {
                loadingDialog.dismiss();
            }
        });
    }

    //上传结果
    private void depositUpdata() {
        loadingDialog.show();
        Map<String, Object> map = new HashMap<>();
        map.put("orderNo", orderNo);
        map.put("payStatus", payStatus);

        MyOkHttpUtils.getServiceDatas(map, Contents.DEPOSIT_UPDATE, new MyOkHttpUtils.ServiceStatus() {
            @Override
            public void success(String response, int d) {
                Loger.e("response", response);
                if (response != null) {
                    JsonAnalysisModel jam = JsonAnalysisUtils.jsonAnalysis(response, CurrencyModel.class);
                    if (jam.isSuccess()) {
                        ToastUtils.showToast("充值成功");
                    } else {
                        ToastUtils.showToast(jam.getMsg());
                    }
                }
                loadingDialog.dismiss();
            }

            @Override
            public void faild(Call call, Exception e, int id) {
                loadingDialog.dismiss();
            }
        });
    }


    @Override
    public void doStartUnionPayPlugin(Activity activity, String s, String s1) {
        UPPayAssistEx.startPay(activity, null, null, s, s1);
    }

    /**
     * 正式支付
     */
    private void startPayMoney() {
        if (NetWork.netWorkType(getApplicationContext()) != 0) {
            String mid = "12492";
            int userId = SpUtils.getInt(TigerWitRechargeActivity.this, "userId", -1);
            String v_url = "http://mayiforex.com/index.html ";
            SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
            java.util.Date data = new java.util.Date(System.currentTimeMillis());
            String curData = formatter.format(data);
            String oid = curData + "-" + mid + "-" + orderNo;
            if (userId == -1) {
                MyApplication.showToast(this, "账号异常，请重新登录！");
                return;
            }
            String mark = userId + "";
            String md5Key = "02Fq3UYefbwJ23ZV";
            createOrder(mid, oid, "", "", "",
                    "", "", rmbAmount + "", curData, "1",
                    "", "0", v_url, "admin",
                    "00", "000000000000000", mark, md5Key);
        } else {
            ViewUtils.toast(TigerWitRechargeActivity.this, "请连接网络!", true);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//        super.onActivityResult(requestCode, resultCode, data);
        if (data != null) {
            String msg = "";
            int msgTag = 0;//1、支付成功 2、支付失败 3、用户取消支付 4、支付异常
            String str = data.getExtras().getString("pay_result");
            if (str != null) {
                if (str.equalsIgnoreCase("success")) {
                    if (data.hasExtra("result_data")) {
                        String builder = data.getExtras().getString("result_data");
                        try {
                            JSONObject resultJson = new JSONObject(builder);
                            String sign = resultJson.getString("sign");
                            String dataOrg = resultJson.getString("data");
                            boolean ret = this.verify(dataOrg, sign, "00");
                            if (ret) {
                                msg = "支付成功！";
                                msgTag = 1;
                            } else {
                                Log.e("success0", builder);
                                msg = "支付失败！";
                                msgTag = 2;
                            }
                        } catch (JSONException var11) {
                        }
                    } else {
                        msg = "支付成功！";
                        msgTag = 1;
                    }
                } else if (str.equalsIgnoreCase("fail")) {
                    msg = "支付失败！";
                    msgTag = 2;
                } else if (str.equalsIgnoreCase("cancel")) {
                    msg = "用户取消了支付";
                    msgTag = 3;
                }
            } else {
                msg = "支付异常";
                msgTag = 4;
            }

            payStatus = str;
            depositUpdata();
            Intent intent = new Intent(this, RechargeResultActivity.class);
            intent.putExtra("rmbAmount", rmbAmount);
            intent.putExtra("rate", rate);
            intent.putExtra("dollar", money);
            if (msgTag == 1) {
                //跳到支付成功页面
                intent.putExtra("status", 0);
            } else {
                //跳转到支付异常界面
                intent.putExtra("status", 1);
            }
            startActivity(intent);

        }
    }

    public boolean verify(String msg, String sign64, String mode) {
        return true;
    }

}
